let hasRenderDom
const container = document.querySelector(".container")

const audio = document.querySelector("audio")
const getLyricsData = () => {
    $.ajax({
        url: "./ly2.json",
        success: res => {
            if (res.code === 200) {
                dealLyricString(res.lrc.lyric)
            }
        }
    })
}
const dealLyricString = (lyricString) => {
    const lyricReg = new RegExp(/[(\u4e00-\u9fa5\a-zA-Z)]/g)
    const msmReg = new RegExp(/\d+/g)
    const lyricsArr = lyricString.split("\n")
    const lyricsAfterDeal = lyricsArr.reduce((acc, current) => {
        if (!current) return [...acc]
        const lyric = current.match(lyricReg)
        const msm = current.match(msmReg).map(item => Number(item))
        const timeSecond = msm[0] * 60 + msm[1] + msm[2] / 1000
        return [...acc, { timing: timeSecond, text: lyric ? lyric.join("") : '' }]
    }, [])
    let fragment = document.createDocumentFragment();
    lyricsAfterDeal.forEach(item => {
        const li = document.createElement("li")
        li.setAttribute("timing", item.timing)
        li.innerHTML = item.text
        fragment.appendChild(li);
    })
    container.appendChild(fragment)
    hasRenderDom = document.querySelectorAll('li')
}
getLyricsData()
const duration = 245;
let current = 0;
container.onclick = (e) => {
    const timing = e.target.getAttribute("timing")
    audio.currentTime = timing
    audio.play()
}
audio.ontimeupdate = e => {
    const index = Array.from(hasRenderDom).findIndex(item => {
        item.setAttribute("class", '')
        return e.target.currentTime < item.getAttribute("timing")
    })
    if (index > 0) {
        let aimNode = hasRenderDom[index - 1]
        aimNode.setAttribute("class", 'active')
        container.scrollTo(0, (aimNode.offsetTop - 150))
    }
}